package uk.co.roguelj.btwave;

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class PrefsActivity extends Activity {
	
	ArrayAdapter <SpinnerDeviceItem> eegBTAdapter;
	ArrayAdapter <SpinnerDeviceItem> hrBTAdapter;
	Spinner eegBTdevs;
	Spinner hrBTdevs;
	EditText hostEditView;
	BluetoothAdapter mBluetoothAdapter;
	Context context;
	String eegMacAddress;
	String hrMacAddress;
	Boolean remoteStatus;
	SharedPreferences prefs;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.settings);
        context = getApplicationContext();       
        hostEditView = (EditText) findViewById(R.id.hostEditText); 
        
        // Set spinner adapters
        eegBTAdapter = new ArrayAdapter <SpinnerDeviceItem> (this, android.R.layout.simple_spinner_item );
        hrBTAdapter = new ArrayAdapter <SpinnerDeviceItem> (this, android.R.layout.simple_spinner_item );
        eegBTAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        hrBTAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
			
		// Get Preferences
		prefs = getPreferences(MODE_PRIVATE);
		eegMacAddress = prefs.getString("EEGMacAddress", "NOTHING");
		hrMacAddress = prefs.getString("HRMacAddress", "NOTHING");
		remoteStatus = prefs.getBoolean("RemoteServerStatus", false);
		
		hostEditView.setText(prefs.getString("RemoteServerAddress", ""));
		
		// Set Event Handler for item change
		eegBTdevs = (Spinner) findViewById(R.id.eegSpinner); 
		eegBTdevs.setOnItemSelectedListener(new OnItemSelectedListener() {
			  		  
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            	eegMacAddress = eegBTAdapter.getItem(position).Device().getAddress();         	
            }

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}

        }); // end set event handler

		// Set Event Handler for item change
		hrBTdevs = (Spinner) findViewById(R.id.hrSpinner); 
		hrBTdevs.setOnItemSelectedListener(new OnItemSelectedListener() {
			  		  
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            	hrMacAddress = hrBTAdapter.getItem(position).Device().getAddress();         	
            }

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}

        }); // end set event handler
		
		setupBT();
		
	} // End onCreate

    // Save button event handler.
    public void save(View v) {
    	   	
    	try {
    		Editor prefsEdit = prefs.edit();	
    		prefsEdit.putString("EEGMacAddress", eegMacAddress);
    		prefsEdit.putString("HRMacAddress", hrMacAddress);
    		prefsEdit.putString("RemoteServerAddress", hostEditView.getText().toString());
    		prefsEdit.putBoolean("RemoteServerStatus", remoteStatus);
        	prefsEdit.commit();		
            
    	} catch (Exception e) {
			Toast toast = Toast.makeText(context, e.getMessage() , Toast.LENGTH_SHORT);
            toast.show();			
            
    	}	

    	finish();
    	 	
    } // end save

    // Cancel button event handler
    public void cancel(View v) {
    	finish();
    }
    
    public CharSequence setupBT() {
    	
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            return "mBluetoothAdapter check fail";
        } // end mBluetoothAdapter check
        
        
    	if (!mBluetoothAdapter.isEnabled()) {
    	    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    	    int ri = 0;
    	    startActivityForResult(enableBtIntent,ri);
    	} // end mBluetoothAdapter enabled check
    
    	
    	Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    	if (pairedDevices.size() > 0) {
    	
    		
    		// Add items to eeg, and set currently selected item
    		int pos1 = 0;
    	    for (BluetoothDevice device : pairedDevices) {
    	    	eegBTAdapter.add(new SpinnerDeviceItem(device));
    	    	if(device.getAddress()==eegMacAddress) {
    	    		pos1 = eegBTAdapter.getCount()-1;
    	    		Log.w("BTWave",device.getAddress() + " " + eegMacAddress);
    	    	}
    	    	
    	    } // end for
    	    eegBTdevs.setAdapter(eegBTAdapter);
    	    eegBTdevs.setSelection(pos1);
    	    
    	    
    	    // Add items to hr, and set currently selected item
    	    int pos2 = 0;
    	    for (BluetoothDevice device : pairedDevices) {
    	    	hrBTAdapter.add(new SpinnerDeviceItem(device));
    	    	if(device.getAddress()==hrMacAddress) pos2 = hrBTAdapter.getCount()-1;
    	    } // end for
    	    hrBTdevs.setAdapter(hrBTAdapter);
    	    hrBTdevs.setSelection(pos2);
    	    
    	    
    	} // end pairedDevices size check
    
    	return "Success " + pairedDevices.size();
    	
    } // end setupBT
    
} // End PrefsActivity class